package ssen.mvc.ondisplay {
import flash.display.DisplayObject;
import flash.events.Event;

import ssen.mvc.core.IDisposable;
import ssen.mvc.core.IInjector;
import ssen.mvc.core.IMediator;

final public class DisplayMediatorController implements IDisposable {
	private var view:DisplayObject;
	private var mediator:IMediator;

	public function DisplayMediatorController(injector:IInjector, view:DisplayObject, mediatorClass:Class=null) {
		this.view=view;

		if (mediatorClass) {
			mediator=injector.instantiate(mediatorClass);
			mediator.setView(view);

			if (view.stage) {
				mediator.onRegister();
				view.addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
			} else {
				view.addEventListener(Event.ADDED_TO_STAGE, addedToStage);
			}
		}
	}

	private function addedToStage(event:Event):void {
		view.removeEventListener(Event.ADDED_TO_STAGE, addedToStage);
		mediator.onRegister();
		view.addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
	}

	private function removedFromStage(event:Event):void {
		dispose();
	}

	public function dispose():void {
		view.removeEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
		mediator.onRemove();
		mediator=null;
		view=null;
	}
}
}
